﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using SmartWarehouse.BussinessLogic.Basis;
using SmartWarehouse.Common;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.txtName.Focus();
            AutoLogin();
        }
    }

    private void AutoLogin()
    {
        if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
        {
            this.txtName.Text = Request.Cookies["UserName"].Value;
            this.txtPassword.Text = Request.Cookies["Password"].Value;
            this.btnLogin_Click(null, null);
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        UserFacade userFacade = new UserFacade();
        SwMessage message = userFacade.CheckUser(this.txtName.Text.Trim(), this.txtPassword.Text.Trim());

        if (message.MessageType == SwMessageType.Ok)
        {
            if(this.chkRememberStatus.Checked)
                WriteCookieOfUser(this.txtName.Text.Trim(), this.txtPassword.Text.Trim());
            this.Session["UserName"] = this.txtName.Text.Trim();
            this.Response.Redirect("~/Welcome.aspx");
        }
        else
        {
            this.errorMessage.InnerText = message.MessageText;
            this.errorMessage.Visible = true;
        }
    }

    private void WriteCookieOfUser(string userName,string password)
    {
        Response.Cookies["UserName"].Value = userName;
        Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(7);

        Response.Cookies["Password"].Value = password;
        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(7);
    }
}
